//
//  shopuserTextViewController.m
//  EasyToTesco
//
//  Created by mc on 16/3/11.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "shopuserTextViewController.h"

#import "ShopUserTableViewCell.h"

#import "AFNetworking.h"

#import "ReadLoginData.h"

#import "SelectBtnView.h"

#import "shopselectView.h"
#import "ReadLoginData.h"


#define WEITH [UIScreen mainScreen].bounds.size.width
#define HIGHT [UIScreen mainScreen].bounds.size.height

#define WEITHRATE [UIScreen mainScreen].bounds.size.width/320
#define HIGHTRATE [UIScreen mainScreen].bounds.size.height/568


#define shopButtonX 108


@interface shopuserTextViewController () <UITableViewDataSource,UITableViewDelegate,ShopSelectViewDelegate,UIAlertViewDelegate>
{
    
    NSInteger orderstate;
    BOOL BtnState;
    
}

@property(nonatomic,assign)BOOL isCash;

@property (nonatomic, strong)NSMutableArray *shopusertextArray;

@property (nonatomic, strong)UITableView *scoreTableView;
@property(nonatomic,strong)UITableView *cashTableView;

/**
 *  记录现金和积分
 */
//@property(nonatomic,strong)NSString *noteStr;

//积分
@property (nonatomic, strong)NSMutableArray *WholeArray;

//现金
@property (nonatomic, strong)NSMutableArray *OilorderArray;

@property (nonatomic, strong)NSMutableArray *dataArr;
//@property (nonatomic, strong)UITableView *MyOrderTableview;
@property (nonatomic, copy)NSString *usernameStr;

// 积分临时数组
@property (nonatomic,strong)NSMutableArray *UpDataJiFenArray;

/**
 *  点击当前行index
 */
@property(nonatomic,strong)NSIndexPath *indexPath;

/**
 *  现金临时数组
 */
@property (nonatomic,strong) NSMutableArray *didClickChangeCell;

/**
 *  保存点击状态修改当前行
 */
@property (nonatomic,assign) BOOL isUpDataCell;

@property (nonatomic,assign) NSInteger buttonIndex;

@end

@implementation shopuserTextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSDictionary *dic = [ReadLoginData readLoginData];
    self.usernameStr = [dic[@"data"] objectForKey:@"username"];
    
    [self addshopusertextinitsth];
    [self addshopuserTexttopview];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.cashTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, HIGHT*0.16, WEITH, HIGHT*0.9)style:UITableViewStyleGrouped];
    self.cashTableView.delegate = self;
    self.cashTableView.dataSource = self;
    [self.view addSubview:self.cashTableView];
    
    self.cashTableView.rowHeight = 110;
    [self addMyOrderUI];
    [self addMyOrderVcinit];
    [self MyOrderDataSources];
    [self MyOrderGethoilDataSources];
    
    self.isUpDataCell = YES;
    
    NSLog(@"isUpDataCell%d",self.isUpDataCell);
}

- (void)addMyOrderVcinit {
    orderstate = 1000;
    BtnState = YES;
    //   usernameStr = @"13282008515";
    self.WholeArray = [@[]mutableCopy];
    self.OilorderArray = [@[]mutableCopy];
    
}
- (void)addMyOrderUI {
    
    shopselectView *selectViewA =[[shopselectView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1, WEITH, HIGHT*0.06)];
    
    selectViewA.delegate = self;
    
    [self.view addSubview:selectViewA];
    
}

-(void)selectBtnClick:(UIButton *)button {
    //    NSLog(@"%@----%ld", button.titleLabel.text, button.tag);
    
    orderstate = button.tag;
    //现金
    if (button.tag == 1000) {
        BtnState = YES;
        [self MyOrderDataSources];
        [self.cashTableView reloadData];
    }
    else if(button.tag == 1001){
        //积分
        BtnState = NO;
        
        [self.cashTableView reloadData];
        [self MyOrderGethoilDataSources];
    }else
    {
        
        //        NSLog(@"%s",__func__);
    }
    
    
}

//现金
- (void)MyOrderGethoilDataSources {
    
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *username = self.usernameStr;
    NSDictionary *param = @{@"username":username,
                            @"fkfs":@2,
                            @"p":@1};
    
    
    [mgr POST:@"http://www.ylgw8.com/AppHz/Gethz" parameters:param success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        if (string.length > 40) {
            self.OilorderArray = [self toArrayOrNSDictionary:responseObject];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"现金暂无数据" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        
        
        //        NSLog(@"现金-------%@", self.WholeArray);
        //    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:self.OilorderArray[0]];
        [self.cashTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}

//积分
- (void)MyOrderDataSources {
    
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *username = self.usernameStr;
    
    
    NSDictionary *param = @{@"username":username,
                            @"fkfs":@3,
                            @"p":@1
                            };
    
    [mgr POST:@"http://www.ylgw8.com/AppHz/Gethz" parameters:param success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        if (string.length > 40) {
            self.WholeArray = [self toArrayOrNSDictionary:responseObject];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"积分暂无数据" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }

        [self.cashTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"shopCell";
    
    ShopUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"ShopUserTableViewCell" owner:nil options:nil] lastObject];
        
    }
    
    if (orderstate == 1000) {
        //        NSLog(@"1000");
        
        //        {
        //            id = 206508, 编号
        //            jine = 200.00, 充值金额
        //            title = 商品名称:Chanpi n,商品数量1, 商品名字
        //            tgf = 16.00,  推广费
        //            username = 18620614920,
        //            fkfs = 3,  消费类型
        //            zt = 2  状态
        //        }
        
        
        
        if ([[self.OilorderArray[indexPath.row] objectForKey:@"zt"] isEqualToString:@"0"] && self.isUpDataCell == YES) {
            cell.statusLabel.hidden = YES;
            cell.didClickButton.hidden = NO;
            //            NSLog(@"状态修改");
        } else {
            cell.statusLabel.hidden = NO;
            cell.didClickButton.hidden = YES;
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            //            switch (self.buttonIndex) {
            //                case 1:
            //                    cell.statusLabel.text = [NSString stringWithFormat:@"状态:%@",@"成功"];
            //                    break;
            //
            //                case 2:
            //                    cell.statusLabel.text = [NSString stringWithFormat:@"状态:失败"];
            //                    break;
            //
            //            }
            
            if(self.buttonIndex == 1) {
                cell.statusLabel.text = [NSString stringWithFormat:@"状态:%@",@"成功"];
                self.buttonIndex = 3;
            } else if (self.buttonIndex == 2) {
                cell.statusLabel.text = [NSString stringWithFormat:@"状态:失败"];
                self.buttonIndex = 3;
            } else {
                
            }
            
            switch ([[self.OilorderArray[indexPath.row] objectForKey:@"zt"] intValue]) {
                case 1:
                    cell.statusLabel.text = [NSString stringWithFormat:@"状态:%@",@"成功"];
                    break;
                    
                case 2:
                    cell.statusLabel.text = [NSString stringWithFormat:@"状态:失败"];
                    break;
                    
                    
            }
            
        }
        
        cell.numberingLabel.text = [NSString stringWithFormat:@"编号:%@",[self.OilorderArray[indexPath.row] objectForKey:@"id"]];
        cell.articleNumberLabel.text = [NSString stringWithFormat:@"购买产品:%@",[self.OilorderArray[indexPath.row] objectForKey:@"title"] ];
        cell.rechargeLabel.text = [NSString stringWithFormat:@"充值金额:%@",[self.OilorderArray[indexPath.row] objectForKey:@"jine"]];
        cell.prepaidUsersLabel.text = [NSString stringWithFormat:@"会员号:%@",[self.OilorderArray[indexPath.row] objectForKey:@"username"]];
        cell.spreadLabel.text = [NSString stringWithFormat:@"推广费:%@",[self.OilorderArray[indexPath.row] objectForKey:@"tgf"]];
        cell.typeLabel.text = @"类型:现金";
        
        
    }else if (orderstate == 1001){
        
        
        if ([[self.WholeArray[indexPath.row] objectForKey:@"zt"] isEqualToString:@"0"] && self.isUpDataCell == YES) {
            cell.statusLabel.hidden = YES;
            cell.didClickButton.hidden = NO;
            //            NSLog(@"状态修改");
        } else {
            //            NSLog(@"%ld",self.buttonIndex);
            
            cell.statusLabel.hidden = NO;
            cell.didClickButton.hidden = YES;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            if(self.buttonIndex == 1) {
                cell.statusLabel.text = [NSString stringWithFormat:@"状态:%@",@"成功"];
                self.buttonIndex = 3;
            } else if (self.buttonIndex == 2) {
                cell.statusLabel.text = [NSString stringWithFormat:@"状态:失败"];
                self.buttonIndex = 3;
            } else {
                
            }
            
            switch ([[self.WholeArray[indexPath.row] objectForKey:@"zt"] intValue]) {
                case 1:
                    cell.statusLabel.text = [NSString stringWithFormat:@"状态:%@",@"成功"];
                    break;
                    
                case 2:
                    cell.statusLabel.text = [NSString stringWithFormat:@"状态:失败"];
                    break;
                    
            }
            
            
        }
        
        cell.numberingLabel.text = [NSString stringWithFormat:@"编号:%@",[self.WholeArray[indexPath.row] objectForKey:@"id"]];
        cell.articleNumberLabel.text = [NSString stringWithFormat:@"购买产品:%@",[self.WholeArray[indexPath.row] objectForKey:@"title"] ];
        cell.rechargeLabel.text = [NSString stringWithFormat:@"充值金额:%@",[self.WholeArray[indexPath.row] objectForKey:@"jine"]];
        cell.prepaidUsersLabel.text = [NSString stringWithFormat:@"会员号:%@",[self.WholeArray[indexPath.row] objectForKey:@"username"]];
        cell.spreadLabel.text = [NSString stringWithFormat:@"推广费:%@",[self.WholeArray[indexPath.row] objectForKey:@"tgf"]];
        
        cell.typeLabel.text = @"类型:积分";
        
        
        
        
    }else{
        
        //        NSLog(@"else");
    }
    return cell;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return 150;
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //    return 1;
    if (orderstate == 1000) {
        return self.OilorderArray.count;
    } else if (orderstate == 1001){
        return self.WholeArray.count;
    }else {
        return self.WholeArray.count;
    }
}

- (void)addshopusertextinitsth {
    NSDictionary *dic = [ReadLoginData readLoginData];
    if (dic.allKeys.count == 0) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未登录,请返回登录" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        
        //        NSLog(@"%@",dic[@"data"]);
        
        [self getuserDataSources:[NSString stringWithFormat:@"%@", [dic[@"data"] objectForKey:@"username"]]];
        
    }
    
    self.shopusertextArray = [@[]mutableCopy];
}

- (void)addshopuserTexttopview {
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 10, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"合作记录";
    
}

- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)getuserDataSources:(NSString *)nameStr {
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *username = nameStr;
    
    NSDictionary *param = @{ @"username":[NSString stringWithFormat:@"%@", username]};
    
    [mgr POST:@"http://www.ylgw8.com/AppHz/Gethz" parameters:param success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",[self toArrayOrNSDictionary:responseObject]);
        
        
        if ([[self toArrayOrNSDictionary:responseObject] isKindOfClass:[NSArray class]]) {
            self.shopusertextArray = [self toArrayOrNSDictionary:responseObject];
        }else {
            
            NSDictionary *dic = [self toArrayOrNSDictionary:responseObject];
            UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"%@", dic[@"message"]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alview show];
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
    
}

// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(self.buttonIndex == 3) return;
    
    
    self.indexPath = indexPath;
#warning 增加+++
    if (orderstate == 1000) {
        [self.didClickChangeCell addObject:self.OilorderArray[indexPath.row]];
        NSLog(@"%@",self.didClickChangeCell);
    }else if (orderstate == 1001) {
         [self.UpDataJiFenArray addObject:self.WholeArray[indexPath.row]];
    }else{
        NSLog(@"%s",__func__);
    }
//    [self.didClickChangeCell addObject:self.OilorderArray[indexPath.row]];
//    NSLog(@"%@",self.didClickChangeCell);
//    [self.UpDataJiFenArray addObject:self.WholeArray[indexPath.row]];

    // 现金
    if (orderstate == 1000) {
        
        if ([[self.didClickChangeCell[0] objectForKey:@"zt"] isEqualToString:@"0"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请点击修改状态" message:nil delegate:self cancelButtonTitle:@"不允许" otherButtonTitles:@"允许", nil];
            
            [alert show];
        } else {
            self.didClickChangeCell = nil;
        }
#warning 改动
    } else if (orderstate == 1001){
        
        if ([[self.UpDataJiFenArray[0] objectForKey:@"zt"] isEqualToString:@"0"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请点击修改状态" message:nil delegate:self cancelButtonTitle:@"不允许" otherButtonTitles:@"允许", nil];
            
            [alert show];
        } else {
            self.UpDataJiFenArray = nil;
        }
    }else{
        
        NSLog(@"%s",__func__);
    }
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
    NSLog(@"buttonIndex%ld",(long)buttonIndex);
    //    NSLog(@"%@",self.didClickChangeCell);
    //    NSLog(@"%d",self.indexPath.row);
    
    
    if (buttonIndex == 0) {
        self.buttonIndex = 2;
    } else {
        self.buttonIndex = 1;
    }
    // 现金
    if (orderstate == 1000) {
        NSLog(@"%@",@(self.buttonIndex));
        NSLog(@"%@",[NSString stringWithFormat:@"%ld",self.buttonIndex]);
        
        NSDictionary *patams = @{
                                 @"id":[self.didClickChangeCell[0] objectForKey:@"id"],
                                 @"clfs":@(self.buttonIndex)
                                 };
        [self upDataDidClickCell:patams];
    }
    
#warning +=
    else if(orderstate == 1001)//积分
    {
        NSDictionary *params = @{
                                 @"id":[self.UpDataJiFenArray[0] objectForKey:@"id"],
                                 @"clfs":@(self.buttonIndex)
                                 };
        [self upDataDidClickCell:params];
    }else{
        
        NSLog(@"%s",__func__);
    }
    
    
    
    
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    //    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.indexPath.row inSection:0];
    //    [self.cashTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationRight];
    
    self.didClickChangeCell = nil;
    self.UpDataJiFenArray = nil;
    
    //    [self.cashTableView reloadData];
}

-(NSMutableArray *)didClickChangeCell {
    if (!_didClickChangeCell) {
        _didClickChangeCell = [NSMutableArray array];
    }
    return _didClickChangeCell;
}

- (NSMutableArray *)UpDataJiFenArray {
    if (!_UpDataJiFenArray) {
        _UpDataJiFenArray = [NSMutableArray array];
    }
    return _UpDataJiFenArray;
}

- (void)upDataDidClickCell :(NSDictionary *)param {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [mgr POST:@"http://www.ylgw8.com/AppHz/Clhz" parameters:param success:^(NSURLSessionDataTask *task, id responseObject) {
        
        self.isUpDataCell = NO;
        
        NSLog(@"%@",[self toArrayOrNSDictionary:responseObject]);
        
        //        [self.cashTableView reloadData];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.indexPath.row inSection:0];
        [self.cashTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationRight];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

@end
